package io.wjc.common;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.io.*;

/**
 * @author: wangjc
 * 2020/4/19
 */
public class BytesSerializer implements RedisSerializer<Object> {
    @Override
    public byte[] serialize(Object serializable) throws SerializationException {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            ObjectOutputStream objStream = new ObjectOutputStream(new BufferedOutputStream(stream));
            objStream.writeObject(serializable);
            objStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stream.toByteArray();
    }

    @Override
    public Object deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null) {
            return null;
        }

        BufferedInputStream stream = new BufferedInputStream(new ByteArrayInputStream(bytes));
        try {
            ObjectInputStream objStream = new ObjectInputStream(stream);
            return objStream.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
